const path = require('path')
const fs = require('fs');

const getDate = require('../utils/date')
const { formalError } = require('../constant/err.type')

const uploadType = async (ctx, next) => {

  const fileTypes = ['image/jpeg', 'image/png']

  const { file } = ctx.request.files
  // console.log(123);
  console.log(file);
  // 获取时间
  const dateT = await getDate()
  // console.log(dateT);
  // 获取地址
  const filePath = path.join(__dirname, '../upload')

  if (fileTypes.includes(file.type)) {
    // 创建可读流
    const reader = fs.createReadStream(file.path);
    // 获取后缀名
    const ext = file.name.split('.').pop();
    // console.log(reader, ext);
    // 创建写入流
    const upStream = fs.createWriteStream(`${filePath}/${dateT}.${ext}`);

    reader.pipe(upStream);

    file.name = `${dateT}.${ext}`


  } else {
    ctx.app.emit('error', formalError, ctx)
    return
  }

  await next()

}

module.exports = { uploadType }